package com.hutao.medical.controller.statics;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hutao.medical.common.config.FunctionType;
import com.hutao.medical.common.util.Constants;
import com.hutao.medical.common.util.CookieUtils;
import com.hutao.medical.common.util.ExcelUtil;
import com.hutao.medical.common.util.Page;
import com.hutao.medical.common.util.Result;
import com.hutao.medical.pojo.borrow.BorrowCheckRecord;
import com.hutao.medical.pojo.borrow.BorrowFunction;
import com.hutao.medical.pojo.borrow.HospitalNote;
import com.hutao.medical.pojo.dto.MedBorrowDto;
import com.hutao.medical.query.BorrowQuery;
import com.hutao.medical.service.BorrowService;
import com.hutao.medical.service.TreatmentTraceService;
import com.hutao.medical.service.TreatmentTraceTypeService;


@RequestMapping("/borrow")
@Controller
public class BorrowController {

	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private BorrowService borrowService;
	
	@Autowired
	private TreatmentTraceService treatmentTraceService;
	
	@Autowired
	private TreatmentTraceTypeService treatmentTraceTypeService;

	@ResponseBody
	@RequestMapping("/addBorrowMed")
	public Result addBorrowMed(String firstGuid, HttpServletRequest request) {
		Result result = null;
		try {
			String currentUser = CookieUtils.getCookieValue(request, "userName");
			
			
			//添加病案信息 
			HospitalNote hospitalNote=borrowService.addHospitalNote(firstGuid);
			
			if(hospitalNote==null){
				 return new Result(false);
			}
			//添加病案借阅信息
			borrowService.addMedRecordBorrow(hospitalNote,currentUser);
			
			//添加示踪记录
			Map<String, Object> treatmentTraceTypeMap = treatmentTraceTypeService.findTreatmentTraceTypeByCode(Constants.BAJY_CODE);
			
			if (treatmentTraceTypeMap != null) {
				Integer traceTypeId =  treatmentTraceTypeMap.get("id") != null ? (Integer)treatmentTraceTypeMap.get("id") : null;
				Map<String, Object> traceMap = new HashMap<String, Object>();
				traceMap.put("firstGuid", firstGuid);
				traceMap.put("loginName", currentUser);
				traceMap.put("traceTypeId", traceTypeId);
				traceMap.put("traceInfo", currentUser + "病案借阅, 病案号为" + hospitalNote.getOnlyId());
				treatmentTraceService.insertTreatmentTrace(traceMap);
			} 
			
			 result = new Result(true);
		} catch (Exception e) {
			e.printStackTrace();
			result = new Result(false);
		}
		return result;
	}

	@ResponseBody
	@RequestMapping("/selectApplyBorrowByKeywords")
	public Result selectApplyBorrowByKeywords(MedBorrowDto medBorrowDto) {
		Result result = null;
		try {
			Map<String, Object> map = borrowService.selectApplyBorrowByKeyWords(medBorrowDto);
			
			result = new Result(true, "查询成功!",map);

		} catch (Exception e) {
			e.printStackTrace();
			result = new Result(false, "查询失败!");
		}
		return result;
	}
	//导出借阅审批到excel
	@RequestMapping("/exportBorrowApproveToExcel")
	public void exportBorrowApproveToExcel(BorrowQuery borrowQuery,HttpServletResponse response){

		List<Map<String,Object>> scanWorkMapList=borrowService.exportBorrowApproveToExcel(borrowQuery);
			try {
				response.setContentType("octets/stream");
		        String excelName = "借阅审批";  
				//转码防止乱码  
				response.addHeader("Content-Disposition", "attachment;filename="+new String(excelName.getBytes("gb2312"), "ISO8859-1" )+".xls");  
				//通过response获取文件输出流
				OutputStream out = response.getOutputStream();

				String title="借阅审批";
				String[] header={"病案号","姓名","证件号码","出院科室","申请时间","申请人"};
				ExcelUtil.exportExcel(out, title, header, scanWorkMapList);
			} catch (Exception e) {
				e.printStackTrace();
				
			}
		
		
	}
	//导出借阅审批到excel
		@RequestMapping("/exportBorrowStaitcsToExcel")
		public void exportBorrowStaitcsToExcel(BorrowQuery borrowQuery,HttpServletResponse response){
			List<Map<String,Object>> scanWorkMapList=new ArrayList<>();
			try {
				response.setContentType("octets/stream");
		        String excelName = "借阅统计";  
				//转码防止乱码  
				response.addHeader("Content-Disposition", "attachment;filename="+new String(excelName.getBytes("gb2312"), "ISO8859-1" )+".xls");  
				//通过response获取文件输出流
				OutputStream out = response.getOutputStream();
			
				//查询数据
				scanWorkMapList=borrowService.exportBorrowStaitcsToExcel(borrowQuery);
				System.out.println(scanWorkMapList.size());
				String title="借阅统计";
				String[] header={"病案号","姓名","出院时间","借阅人","借阅时间"};
				ExcelUtil.exportExcel(out, title, header, scanWorkMapList);
			} catch (Exception e) {
				e.printStackTrace();
				
			}
		}

	@ResponseBody
	@RequestMapping("/updateApplyStatus")
	public Result updateApplyStatus(BorrowFunction borrowFunction, String firstGuid, String onlyId, HttpServletRequest request) {
		Result result = null;
		try {
			String currentUser = CookieUtils.getCookieValue(request, "userName");
			borrowFunction.setCheckMan(currentUser);
			borrowFunction.setCheckTime(new Date());
			borrowService.updateApplyStatus(borrowFunction);

			//审核通过才记录到示踪
			if (borrowFunction != null && borrowFunction.getCheckStatus() == Constants.MEDICAL_BORROW_AGREE) {
				Map<String, Object> treatmentTraceTypeMap = treatmentTraceTypeService.findTreatmentTraceTypeByCode(Constants.BAJYSP_CODE);
				
				if (treatmentTraceTypeMap != null) {
					Integer traceTypeId =  treatmentTraceTypeMap.get("id") != null ? (Integer)treatmentTraceTypeMap.get("id") : null;
					Map<String, Object> traceMap = new HashMap<String, Object>();
					traceMap.put("firstGuid", firstGuid);
					traceMap.put("loginName", currentUser);
					traceMap.put("traceTypeId", traceTypeId);
					traceMap.put("traceInfo", currentUser + "病案借阅审批, 住院号为" + onlyId);
					treatmentTraceService.insertTreatmentTrace(traceMap);
				} 
			}
			
			result = new Result(true, "更新成功");
		} catch (Exception e) {
			e.printStackTrace();
			result = new Result(false, "更新失败");
		}
		return result;
	}

	/**
	 * @author yimr
	 * @param borrowCheckRecord
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateApplyStatusBacth")
	public Result updateApplyStatusBacth(BorrowCheckRecord borrowCheckRecord, HttpServletRequest request) {
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		borrowCheckRecord.setCheckMan(currentUser);
		Result result = null;
		try {
			int count = borrowService.updateApplyStatusBatch(borrowCheckRecord);
			if (count > 0) {
				result = new Result(true, "批量更新成功");
			} else {
				result = new Result(false, "批量更新失败");
			}

		} catch (Exception e) {
			result = new Result(false, "批量更新失败");
		}
		return result;
	}

	@ResponseBody
	@RequestMapping("/selectBorrowMedByLoginNameAndDays")
	public Result selectBorrowMedByLoginNameAndDays(HttpServletRequest request,MedBorrowDto medBorrowDto) {
		Result result = null;
		try {
			String currentUser = CookieUtils.getCookieValue(request, "userName");
			medBorrowDto.setApplyName(currentUser);
			Map<String,Object> map = borrowService.selectBorrowMedByLoginNameAndDays(medBorrowDto);
			
			result = new Result(true, "查询成功!", map);
		} catch (Exception e) {
			e.printStackTrace();
			result = new Result(false, "查询借阅信息出现错误:{}=" + e.getMessage());
		}
		return result;
	}
	
	/**
	 * 移动端借阅查看
	 * 
	 * @param request
	 * @param medBorrowDto
	 * @return
	 */
	@ResponseBody
	@PostMapping("/selectBorrowMedByLoginNameAndDays_mobile")
	public Result selectBorrowMedByLoginNameAndDays_mobile(@RequestParam(value = "page", defaultValue = "1") int currentPage, 
			String status, String userName, HttpServletRequest request) {
		try {
			Map<String, Object> params = new HashMap<>();
			Page page = new Page();
			page.setCurrentPage(currentPage);
			page.setPageSize(10);
			params.put("applyName", userName);
			params.put("status", status);
			params.put("functionType", FunctionType.borrow);
			params.put("page", page);
			List<Map<String, Object>> list = borrowService.getMedicalBorrowSearchList_mobile(params);
			int count = borrowService.getMedicalBorrowSearchListCount_mobile(params);
			page.setList(list);
			page.setRows(count);
			return new Result(true, "查询成功!", page, 200);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("病案借阅移动端查询异常---" + e);
			return new Result(false, "系统异常!", null , 500);
		}
	}

	/**
	 * 查看借阅信息
	 * 
	 * @param firstGuid
	 *            诊疗记录firstGuid
	 * @param applyName
	 *            水印内容
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/showMedrecordImage")
	public String showMedrecordImage(String firstGuid, String applyName, Model model, HttpServletRequest request) {
		// 水印图片信息和住院记录
		
		try {
			applyName = URLDecoder.decode(applyName, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Map<String, Object> resultMap = borrowService.getMedResourceFile(firstGuid, applyName);
		model.addAttribute("resultMap", resultMap);
		return "statics/showMedrecordImage";
	}

	/**
	 * 查看水印图片信息
	 * 
	 * @param firstGuid
	 *            诊疗记录firstGuid
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/showMedrecordMarkImage")
	public String showMedrecordMarkImage(String firstGuid, Model model, HttpServletRequest request) {
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		// 水印图片信息和住院记录
		Map<String, Object> resultMap = borrowService.getMedResourceFile(firstGuid, currentUser);
		model.addAttribute("resultMap", resultMap);
		return "statics/showMedrecordMarkImage";
	}
	
	@ResponseBody
	@RequestMapping("/getMedicalBorrowListToCheck")
	public Result getMedicalBorrowListToCheck(MedBorrowDto medBorrowDto){
		Result result = null;
		try {
			Map<String,Object> map = borrowService.getMedicalBorrowListToCheck(medBorrowDto);
			 result = new Result(true,"查询成功!",map);
		} catch (Exception e) {
			 result = new Result(false,"查询失败!");
		}
		return result;
	}
	
	/**
	 * 移动端添加借阅记录
	 * 
	 * @param firstGuid
	 * @param request
	 * @return
	 */
	@ResponseBody
	@PostMapping("/addBorrowMed_mobile")
	public Result addBorrowMed_mobile(String firstGuid,  String userName, HttpServletRequest request) {
		Result result = null;
		try {
			//添加病案信息 
			HospitalNote hospitalNote=borrowService.addHospitalNote(firstGuid);
			
			if(hospitalNote==null){
				 return new Result(false);
			}
			//添加病案借阅信息
			borrowService.addMedRecordBorrow(hospitalNote, userName);
			
			//添加示踪记录
			Map<String, Object> treatmentTraceTypeMap = treatmentTraceTypeService.findTreatmentTraceTypeByCode(Constants.BAJY_CODE);
			
			if  (treatmentTraceTypeMap != null) {
				Integer traceTypeId =  treatmentTraceTypeMap.get("id") != null ? (Integer)treatmentTraceTypeMap.get("id") : null;
				Map<String, Object> traceMap = new HashMap<String, Object>();
				traceMap.put("firstGuid", firstGuid);
				traceMap.put("loginName", userName);
				traceMap.put("traceTypeId", traceTypeId);
				traceMap.put("traceInfo", userName + "病案借阅, 病案号为" + hospitalNote.getOnlyId());
				treatmentTraceService.insertTreatmentTrace(traceMap);
			} 
			 result = new Result(true, "添加成功!", null, 200);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("-------移动端添加病案信息失败--------" + e);
			result = new Result(false, "系统异常!", null, 500);
		}
		return result;
	}
	
	
}


